<template>
  <!--  -->
  <Dialog
    ref="dialog"
    :dialog-actions="dialogActions"
    :visible.sync="dialogActions.visible"
    @close="close"
    @confirm="handleSubmit"
  >
    <template slot="content">
      <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="10" class="dialog-from-style">
          <el-col
            v-for="(field, index) in fields"
            :key="index"
            :span="field.colSpan || 12"
            class="form-col-item-dynamic"
          >
            <el-form-item
              v-if="isShow(field)"
              :key="index"
              :label="field.label"
              :prop="field.prop"
              :rules="field.rules"
            >
              <component
                :is="getComponentConfig(field.type).component"
                v-model="formData[field.prop]"
                v-bind="getComponentProps(field)"
                @change="changeEmit(field.prop, formData[field.prop], field)"
                v-on="getComponentEvents(field, formData)"
              >
                <component
                  v-for="(child, i) in getComponentChildren(field)"
                  :is="child.component"
                  v-bind="child.props"
                >
                  {{ child.content }}
                </component>
              </component>
              <div v-if="field.tip" class="form-tip">{{ field.tip }}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
  </Dialog>
</template>

<script>
import Dialog from "@/components/DynamicTableForm/Dialog/index.vue";
import { componentMap } from "@/components/DynamicTableForm/Form/componentMap.js";
import {
  fieldsValidator,
  getComponentEvents,
  getDefaultPlaceholder,
} from "@/components/DynamicTableForm/Form/fieldsValidator.js";
// import request from "@/utils/request";
// import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "DynamicForm",
  components: {
    Dialog,
  },
  props: {
    FormConfig: {
      type: Object,
      default: () => ({
        key: "", // 判断接口类型
        details: {
          url: "",
        },
        id: "",
        dialogActions: {
          visible: false,
          title: "示例",
        },
        fields: {
          type: Array,
          required: true,
          validator: (value) => fieldsValidator(value),
        },
        initialData: {
          type: Object,
          default: () => ({}),
        },
      }),
    },
  },
  data() {
    return {
      componentMap,
      dialogActions: {
        visible: false,
        title: this.FormConfig.id ? "编辑" : "新增",
      },
      fields: [],
      ...this.FormConfig,
      formData: {},
      formRules: {},
    };
  },
  // 如果动态加载组件
  watch: {
    "FormConfig.dialogActions.visible": {
      handler(val) {
        if (val && this.FormConfig.details?.url) {
          // 判断如果有传API url 的话，请求数据，没有就默认获取列表数据
          if (this.FormConfig.details?.url) {
            this.Request(this.FormConfig.details, this.FormConfig.details.params)
            .then(
              (res) => {
                this.formData = res.data;
                this.$emit("initCallback", this.formData);
              }
            );
          }
        }
      },
      immediate: false,
    },
    'FormConfig.initialData': {
      handler(newVal) {
        console.log(newVal, "init");
        this.$nextTick(() => {
          this.formData = newVal;
        });
      },
      deep: true,
    },
  },
  mounted() {},
  methods: {
    // 方法挂载
    getComponentEvents,
    // 初始化表单
    initForm() {
      this.formData = this.fields.reduce(
        (acc, field) => ({
          ...acc,
          [field.prop]:
            this.initialData[field.prop] ?? this.getDefaultValue(field.type),
        }),
        {}
      );

      this.formRules = this.fields.reduce(
        (acc, field) =>
          field.rules ? { ...acc, [field.prop]: field.rules } : acc,
        {}
      );
    },

    handleSubmit() {
      console.log(this.formData);
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit("submitCallback", this.formData);
          if (this.FormConfig.id) {
            this.Request(this.FormConfig.edit, this.formData).then((res) => {
              this.successMsg(res);
            });
          }else {
            this.Request(this.FormConfig.add, this.formData).then((res) => {
              this.successMsg(res);
            });
          }
        }
      });
    },
    Request(config, params = {}) {
      return new Promise((resolve, reject) => {
        request({
          url: config?.url,
          method: config?.method || "POST",
          data: params,
        })
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    successMsg(res) {
      if ([200].includes(res.code)) {
        this.$message({
          type: "success",
          message: "提交成功！",
        });
        this.$emit("successCallback", res);
        this.dialogActions.visible = false;
      }
    },
    open() {
      this.dialogActions.visible = true;
    },
    close() {
      console.log(8881);
      this.$emit("update:visible", false);
      this.$refs.form.resetFields();
      this.dialogActions.visible = false;
    },

    getComponentConfig(type) {
      return this.componentMap[type] || this.componentMap.default;
    },
    // 生成子组件
    getComponentChildren(field) {
      const config = componentMap[field.type];
      return config.children
        ? typeof config.children === "function"
          ? config.children(field.options)
          : config.children
        : [];
    },

    // 获取类型默认值
    getDefaultValue(type) {
      const typeDefaults = {
        "checkbox-group": [],
        "radio-group": 0,
        "input-number": 0,
        slider: 0,
        rate: 0,
        switch: 1,
        upload: [],
      };
      return typeDefaults[type] ?? "";
    },

    // 获取组件属性
    getComponentProps(field) {
      const config = this.getComponentConfig(field.type);
      return {
        // 优先级顺序：用户配置 > 组件默认配置
        ...config.props, // 1. 组件默认配置
        ...field.props, // 2. 用户自定义配置
        // 特殊属性处理
        style: "width: 100%", // 强制宽度
        placeholder: field.placeholder || getDefaultPlaceholder(field.type),
      };
    },

    // 其他核心方法...
    isShow(row) {
      if (!row.isShow) return true;
      // console.log(typeof row.isShow === 'boolean')
      return typeof row.isShow === "boolean" ? row.isShow : true;
    },
    changeEmit(key, value, row) {
      this.$emit("changeAll", key, value, row);
    },
  },
};
</script>
